package cool.taomu.toolkit.provider

import com.google.inject.Inject
import com.google.inject.Provider
import java.util.Properties
import javax.inject.Named
import javax.mail.Authenticator
import javax.mail.PasswordAuthentication
import javax.mail.Session
import org.slf4j.LoggerFactory

class EmailProvider implements Provider<Session> {
    val static LOG = LoggerFactory.getLogger(EmailProvider);
    
	@Inject(optional=true)
	@Named("taomu.mail.smtp.host")
	String host;
	
	@Inject
	@Named("taomu.mail.from")
	String from;

	@Inject(optional=true)
	@Named("taomu.mail.smtp.pwd")
	String pwd;

	@Inject(optional=true)
	@Named("taomu.mail.smtp.port")
	int port = 465;

	@Inject(optional=true)
	@Named("taomu.mail.smtp.auth")
	boolean auth = true;

	@Inject(optional=true)
	@Named("taomu.mail.smtp.starttls.enable")
	boolean enable = true;
	
	
	@Inject(optional=true)
	@Named("taomu.mail.smtp.scoketFactory")
	String scoketFactory;

	override get() {
	    LOG.info("设置邮箱服务器")
		var props = new Properties();
		props.put("mail.smtp.host", host.trim);
		props.put("mail.smtp.port", port);
		props.put("mail.smtp.auth", auth);
		props.put("mail.smtp.starttls.enable", enable);
		if(scoketFactory !== null){
			props.put("mail.smtp.socketFactory.class", scoketFactory.trim);
		}

		return Session.getInstance(props, new Authenticator() {
			override getPasswordAuthentication() {
				return new PasswordAuthentication(from.trim, pwd.trim);
			}
		})
	}
}
